import type { Router, LocationQueryRaw } from 'vue-router'

import { useUserStore } from '@/store'
import { isLogin } from '@/utils/common/auth'

import NProgress from 'nprogress'

NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: false, // 是否显示加载icon
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 初始化时的最小百分比
  parent: '#app',
})

export default function useLoginGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    console.log(to, 'to')

    NProgress.start()

    if (isLogin()) {
      console.log('success')
      next()
    } else {
      /**
       * 未登入执行逻辑
       */

      const fxPath = [
        '/cvmagic/login',
        '/cvmagic/register',
        '/cvmagic/register/store',
        '/cvmagic/register/qualification',
      ]
      //当前跳转路径为登入页则放行
      if (fxPath.includes(to.path)) {
        next()
        return
      }

      //重定向到登入页面
      next({
        path: '/cvmagic/login',
        query: {
          redirect: to.name,
          ...to.query,
        } as LocationQueryRaw,
      })
    }
  })

  router.afterEach(() => {
    // 在即将进入新的页面组件前，关闭掉进度条
    NProgress.done()
  })
}
